<template>
  <van-config-provider :theme-vars="themeVars">
    <van-dropdown-menu class="cinemas-dropdown" ref="districtDropdown">
      <!--区域 -->
      <van-dropdown-item :title="dropdownDistrictTitle" v-model="regionIndex" @change="changeDropdown">
        <van-tabs @click-tab="onClickTab" v-model:active="tabActive">
          <van-tab title="商区">
            <van-tree-select v-model:main-active-index="districtIndex" v-model:active-id="areaId"
              @click-nav="distHandleClickNav" @click-item="distHandleClickItem" :items="districtItems">
            </van-tree-select>
          </van-tab>
          <van-tab title="地铁站">
            <van-tree-select v-model:main-active-index="lineIndex" v-model:active-id="stationId"
              @click-nav="subHandleClickNav" @click-item="subHandleClickItem" :items="subwayItems">
            </van-tree-select>
          </van-tab>
        </van-tabs>
      </van-dropdown-item>

      <!--- 排序 --->

      <van-dropdown-item :title="dropdownSortTitle" v-model="sortId" @change="changeSort" :options="sortOption">
      </van-dropdown-item>

      <!--品牌 -->
      <van-dropdown-item :title="dropdownBrandTitle" v-model="brandIndex" @change="changeBrand" :options="brandOption">
      </van-dropdown-item>

      <!--筛选 -->
      <van-dropdown-item :title="dropdownSpecialTitle" v-model="serviceIds">
        <div class="special">
          <h5>{{ service.name }}</h5>
          <van-grid :border="false" :clickable="true" gutter="5">
            <van-grid-item v-for="item in service.subItems" :key="item.id" @click="handleServiceClick(item)">
              <van-button plain hairline block size="normal" class="special-btn"
                :class="{ 'active-btn': serviceIds === item.id }">{{ item.name }}</van-button>
            </van-grid-item>
          </van-grid>

          <h5 style="margin-top: 10px">{{ hallType.name }}</h5>
          <van-grid :border="false" :clickable="true" :gutter="5">
            <van-grid-item v-for="item in hallType.subItems" :key="item.id" @click="handleHallTypeClick(item)">
              <van-button plain hairline block size="normal" class="special-btn"
                :class="{ 'active-btn': hallTypeId === item.id }">{{ item.name }}</van-button>
            </van-grid-item>
          </van-grid>

          <van-divider />

          <van-row justify="space-between" align="center">
            <van-col>
              <van-button plain hairline block size="normal" type="default" class="reset"
                @click="onReset">重置</van-button>
            </van-col>
            <van-col>
              <van-button plain hairline block size="normal" type="default" color="#e54847" class="confirm"
                @click="onConfirm">确定</van-button>
            </van-col>
          </van-row>
        </div>
      </van-dropdown-item>
    </van-dropdown-menu>

    <!-- 影院列表 -->
    <van-list class="list" v-model:loading="loading" :finished="finished" finished-text="没有更多了" @load="onLoad">
      <ul>
        <li v-for="cinema in cinemas" :key="cinema.id" class="cinema-item" @click="goToCinemaDetail(cinema.id)">
          <div class="name-price">
            <div class="name  line-ellipsis">{{ cinema.name }}</div>
            <div class="price line-ellipsis">{{ cinema.sellPrice }}<span>元起</span></div>
          </div>
          <div class="address-distance">
            <div class="address line-ellipsis">{{ cinema.addr }}</div>
            <div class="distance line-ellipsis">{{ calculateDistance(store.geolocation.latitude,
              store.geolocation.longitude, cinema.lat, cinema.lng) }} km</div>
          </div>
          <div class="services">
            <van-tag plain :color="label.color" v-for="(label, index) in cinema.labels" :key="index" class="service">{{
              label.name
              }}</van-tag>
          </div>

          <div class="showTimes">{{ cinema.showTimes }}</div>
        </li>
      </ul>
    </van-list>
  </van-config-provider>
</template>

<script setup>
import { fetchMovieCinemaFilter, fetchMovieCinemaListByFilter } from '@/api/index.js'
import { calculateDistance } from "@/tools/index.js"

import { ref, onMounted, computed, watch, reactive } from 'vue'
import { useRoute, useRouter } from 'vue-router'
const route = useRoute()
const router = useRouter()

import { useStore } from '@/stores/index.js'
const store = useStore()

const movieId = computed(() => route.params.movieId)



const props = defineProps({
  activeShowDate: {
    type: String,
  },
})
const activeShowDate = computed(() => props.activeShowDate)

const themeVars = reactive({
  gridItemContentPadding: '0px',
  buttonDefaultColor: '#777',
})

const loading = ref(false)
const finished = ref(false)
const tabActive = ref(0)

const sortOption = ref([
  { text: '距离优先', value: 0 },
  { text: '低价优先', value: 1 },
])

const sort = computed(() => {
  switch (sortId.value) {
    case 0:
      return 'distance'
    case 1:
      return 'price'
    default:
      return 'distance' // 默认值
  }
})

const district = ref({})
const brand = ref({})
const service = ref({})
const hallType = ref({})
const subway = ref({})

const dropdownDistrictTitle = ref('全城') // 初始标题

const dropdownSortTitle = ref('排序') // 初始标题

const dropdownBrandTitle = ref('品牌') // 初始标题

const serviceTitle = ref('全部')
const hallTypeTitle = ref('全部')

const dropdownSpecialTitle = computed(() => {
  const service = serviceTitle.value
  const hallType = hallTypeTitle.value

  if (service === '全部' && hallType === '全部') {
    return '特色'
  }
  if (service === '全部' && hallType != '全部') {
    return hallType
  }
  if (hallType === '全部' && service != '全部') {
    return service
  }
  return `${service},${hallType}`
})

const regionIndex = ref(0) //  行政区 or 地铁

const districtIndex = ref(0) //  行政区 索引

const districtId = ref(-1) //行政区
const areaId = ref(-1) //商区

const lineIndex = ref(0) //  地铁 索引

const lineId = ref(-1) // 地铁线路 默认全部
const stationId = ref(-1) //  地铁站点 默认全部

const sortId = ref(0) // 排序索引

const brandIndex = ref(0)
const brandIds = ref([-1])
const serviceIds = ref([-1])

const hallTypeIds = ref(['all'])
const languageIds = ref(['all'])
const dimIds = ref(['all'])

const cinemas = ref([])
const pageNum = ref(1)
const limit = ref(20)

const offset = computed(() => {
  return (pageNum.value - 1) * limit.value
})

// 获取 van-dropdown-item 的实例
const districtDropdown = ref(null)

const districtItems = ref([])
const subwayItems = ref([])
const brandOption = ref([])
// const specialOption = ref([])

// 商圈数据转换
function transformDistrictData (district) {
  return district.subItems.map((item, index) => {
    // console.log('item:', item); // 打印每个元素，检查是否有异常
    return {
      index: index, // 行政区 索引
      id: item.id, //行政区ID
      text: item.name + '(' + item.count + ')', //行政区名称 + 数量
      count: item.count,
      children: item.subItems.map((subItem) => {
        return {
          text: subItem.name + '(' + subItem.count + ')', //商圈名 + 数量
          id: subItem.id, // 商区实际的ID
          count: subItem.count,
        }
      }),
    }
  })
}

//地铁数据转化
function transformSubwayData (subway) {
  return subway.subItems.map((item, index) => {
    return {
      index: index, //地铁 索引
      id: item.id, //地铁线路 ID  lineId
      text: item.name, // 地铁线路名称
      count: item.count,
      children: item.subItems.map((subItem) => {
        return {
          text: subItem.name, // 地铁 站点名称
          id: subItem.id, // 地铁 站点ID
          count: subItem.count,
        }
      }),
    }
  })
}

// 电影院筛选条件
const getMovieCinemaFilter = async () => {
  // 电影院筛选条件
  const res = await fetchMovieCinemaFilter(
    movieId.value,
    store.currentCity.id,
    activeShowDate.value,
  )
  brand.value = res.data?.brand
  district.value = res.data?.district || {}
  hallType.value = res.data?.hallType || {}
  service.value = res.data?.service || {}
  subway.value = res.data?.subway || {}

  // 行政区商圈数据填充
  districtItems.value = transformDistrictData(district.value)

  // 地铁数据填充
  subwayItems.value = transformSubwayData(subway.value)

  //填充品牌
  brand.value.subItems.forEach((item, index) => {
    brandOption.value.push({
      text: item.name,
      count: item.count,
      value: item.id,
      id: item.id,
      index: index,
    })
  })

  // console.log("getMovieCinemaFilter", res.data);
}

// 根据筛选结果查询电影院列表
const getMovieCinemaListByFilter = async (
  offset,
  limit,
  showDate,
  movieId,
  sort,
  cityId,
  latitude,
  longitude,
  districtId,
  lineId,
  areaId,
  stationId,
  brandIds,
  serviceIds,
  hallTypeIds,
  languageIds,
  dimIds,
) => {

  loading.value = true
  const response = await fetchMovieCinemaListByFilter(
    offset,
    limit,
    showDate,
    movieId,
    sort,
    cityId,
    latitude,
    longitude,
    districtId,
    lineId,
    areaId,
    stationId,
    brandIds,
    serviceIds,
    hallTypeIds,
    languageIds,
    dimIds,
  )
  // console.log('response', response)
  loading.value = false

  cinemas.value.push(...response.data.cinemas)
  // console.log('cinemas.value', cinemas.value)
  store.setCinemas(cinemas.value) //当前电影院
  if (response.data.paging.hasMore === false) {
    finished.value = true
    return
  }
}

onMounted(async () => {
  // 加载电影院筛选条件
  await getMovieCinemaFilter()
  // console.log('serviceIds', serviceIds.value)
  // console.log('hallTypeIds', hallTypeIds.value)
  // console.log('languageIds', languageIds.value)
  // console.log('dimIds', dimIds.value)
  // 默认加载全部电影院列表
  cinemas.value = [] // 清空电影院列表
  finished.value = false // 重置finished状态
  pageNum.value = 1 // 页码重置为1
  await getMovieCinemaListByFilter(
    offset.value,
    limit.value,
    activeShowDate.value,
    movieId.value,
    sort.value,
    store.currentCity.id,
    store.geolocation.latitude,
    store.geolocation.longitude,
    districtId.value,
    lineId.value,
    areaId.value,
    stationId.value,
    brandIds.value,
    serviceIds.value,
    hallTypeIds.value,
    languageIds.value,
    dimIds.value,
  )
})

const onLoad = async () => {
  // 加载更多电影院列表
  pageNum.value = pageNum.value + 1 // 页码加1，尝试加载更多
  await getMovieCinemaListByFilter(
    offset.value,
    limit.value,
    activeShowDate.value,
    movieId.value,
    sort.value,
    store.currentCity.id,
    store.geolocation.latitude,
    store.geolocation.longitude,
    districtId.value,
    lineId.value,
    areaId.value,
    stationId.value,
    brandIds.value,
    serviceIds.value,
    hallTypeIds.value,
    languageIds.value,
    dimIds.value,
  )
}

// 监听行政区变化
watch(districtId, async (newDistrictId) => {
  pageNum.value = 1 // 页码重置为1
  cinemas.value = [] // 清空电影院列表
  finished.value = false // 重置finished状态
  if (newDistrictId === -1) {
    areaId.value = -1
  }
  await getMovieCinemaListByFilter(
    offset.value,
    limit.value,
    activeShowDate.value,
    movieId.value,
    sort.value,
    store.currentCity.id,
    store.geolocation.latitude,
    store.geolocation.longitude,
    newDistrictId,
    lineId.value,
    areaId.value,
    stationId.value,
    brandIds.value,
    serviceIds.value,
    hallTypeIds.value,
    languageIds.value,
    dimIds.value,
  )
})

// 监听商圈变化
watch(areaId, async (newAreaId) => {
  pageNum.value = 1 // 页码重置为1
  cinemas.value = [] // 清空电影院列表
  finished.value = false // 重置finished状态
  await getMovieCinemaListByFilter(
    offset.value,
    limit.value,
    activeShowDate.value,
    movieId.value,
    sort.value,
    store.currentCity.id,
    store.geolocation.latitude,
    store.geolocation.longitude,
    districtId.value,
    lineId.value,
    newAreaId,
    stationId.value,
    brandIds.value,
    serviceIds.value,
    hallTypeIds.value,
    languageIds.value,
    dimIds.value,
  )
})

// 监听地铁线路变化
watch(lineId, async (newlineId) => {
  pageNum.value = 1 // 页码重置为1
  cinemas.value = [] // 清空电影院列表
  finished.value = false // 重置finished状态
  if (newlineId === -1) {
    stationId.value = -1
  }
  await getMovieCinemaListByFilter(
    offset.value,
    limit.value,
    activeShowDate.value,
    movieId.value,
    sort.value,
    store.currentCity.id,
    store.geolocation.latitude,
    store.geolocation.longitude,
    districtId.value,
    newlineId,
    areaId.value,
    stationId.value,
    brandIds.value,
    serviceIds.value,
    hallTypeIds.value,
    languageIds.value,
    dimIds.value,
  )
})

// 监听地铁站点变化
watch(stationId, async (newStationId) => {
  pageNum.value = 1 // 页码重置为1
  cinemas.value = [] // 清空电影院列表
  finished.value = false // 重置finished状态
  await getMovieCinemaListByFilter(
    offset.value,
    limit.value,
    activeShowDate.value,
    movieId.value,
    sort.value,
    store.currentCity.id,
    store.geolocation.latitude,
    store.geolocation.longitude,
    districtId.value,
    lineId.value,
    areaId.value,
    newStationId,
    brandIds.value,
    serviceIds.value,
    hallTypeIds.value,
    languageIds.value,
    dimIds.value,
  )
})

//监听 排序变化
watch(sortId, async (newSortId) => {
  pageNum.value = 1 // 页码重置为1
  cinemas.value = [] // 清空电影院列表
  finished.value = false // 重置finished状态
  //如果是距离排序 newSortId ===0
  // 如果是价格排序 newSortId===1
  const sort = sortOption.value[newSortId].text
  await getMovieCinemaListByFilter(
    offset.value,
    limit.value,
    activeShowDate.value,
    movieId.value,
    sort,
    store.currentCity.id,
    store.geolocation.latitude,
    store.geolocation.longitude,
    districtId.value,
    lineId.value,
    areaId.value,
    stationId.value,
    brandIds.value,
    serviceIds.value,
    hallTypeIds.value,
    languageIds.value,
    dimIds.value,
  )
})

//监听品牌变化
watch(brandIds, async (newBrandIds) => {
  pageNum.value = 1 // 页码重置为1
  cinemas.value = [] // 清空电影院列表
  finished.value = false // 重置finished状态
  await getMovieCinemaListByFilter(
    offset.value,
    limit.value,
    activeShowDate.value,
    movieId.value,
    sort.value,
    store.currentCity.id,
    store.geolocation.latitude,
    store.geolocation.longitude,
    districtId.value,
    lineId.value,
    areaId.value,
    stationId.value,
    newBrandIds,
    serviceIds.value,
    hallTypeIds.value,
    languageIds.value,
    dimIds.value,
  )
})
// 监听日期变化
watch(activeShowDate, async (newShowDate) => {
  console.log('activeShowDate changed to:', newShowDate) // 添加日志
  pageNum.value = 1 // 页码重置为1
  cinemas.value = [] // 清空电影院列表
  finished.value = false // 重置finished状态
  await getMovieCinemaListByFilter(
    offset.value,
    limit.value,
    newShowDate,
    movieId.value,
    sort.value,
    store.currentCity.id,
    store.geolocation.latitude,
    store.geolocation.longitude,
    districtId.value,
    lineId.value,
    areaId.value,
    stationId.value,
    brandIds.value,
    serviceIds.value,
    hallTypeIds.value,
    languageIds.value,
    dimIds.value,
  )
})

const changeDropdown = (value) => { }

const changeSort = (value) => {
  // console.log("changeSort", index);

  sortId.value = value
  dropdownSortTitle.value = sortOption.value[value].text
}

const changeBrand = (value) => {
  console.log('value', value)
  brandIds.value = [value]
  dropdownBrandTitle.value = brandOption.value.find((item) => item.value === value).text
  brandIndex.value = brandOption.value.find((item) => item.value === value).value
}

// 商区一级筛选 行政区
const distHandleClickNav = (index) => {
  districtId.value = districtItems.value[index].id // 点击的行政区ID
  // 更新 dropdown-item 的标题
  if (districtItems.value[index].id !== -1) {
    dropdownDistrictTitle.value = districtItems.value[index].text
  } else {
    dropdownDistrictTitle.value = '全城'
  }
  // 关闭下拉菜单
  if (index === 0) {
    districtDropdown.value.close()
  }
}
// 商区二级筛选  商圈
const distHandleClickItem = (item) => {
  areaId.value = item.id //点击的商圈ID
  // 更新 dropdown-item 的标题
  if (item.id !== -1) {
    dropdownDistrictTitle.value = item.text
  } else {
    dropdownDistrictTitle.value = districtItems.value[districtIndex.value].text
  }
  // 关闭下拉菜单
  districtDropdown.value.close()
}

// 地铁一级筛选  地铁几号线？
const subHandleClickNav = (index) => {
  lineId.value = subwayItems.value[index].id // 点击的行政区ID

  // console.log("lineId", lineId.value);
  // 更新 dropdown-item 的标题
  if (subwayItems.value[index].id !== -1) {
    dropdownDistrictTitle.value = subwayItems.value[index].text
  } else {
    dropdownDistrictTitle.value = '全城'
  }
  // 关闭下拉菜单
  if (index === 0) {
    districtDropdown.value.close()
  }
}

// 地铁二级筛选  地铁站?
const subHandleClickItem = (item) => {
  stationId.value = item.id //点击的商圈ID

  // console.log("stationId", stationId.value);
  // 更新 dropdown-item 的标题
  if (item.id !== -1) {
    dropdownDistrictTitle.value = item.text
  } else {
    dropdownDistrictTitle.value = subwayItems.value[lineIndex.value].text
  }
  // 关闭下拉菜单
  districtDropdown.value.close()
}

// 特色 影院服务
const handleServiceClick = (item) => {
  console.log('handleServiceClick', item)

  serviceIds.value = [item.id]
  serviceTitle.value = item.name
}

//特色 影厅类型
const handleHallTypeClick = (item) => {
  // console.log('handleHallTypeClick', item)
  hallTypeIds.value = [item.id]
  hallTypeTitle.value = item.name
}

// 重置
const onReset = () => {
  serviceIds.value = [-1]

  languageIds.value = ['all']
  hallTypeIds.value = ['all']
  dimIds.value = ['all']

  serviceTitle.value = '全部'
  hallTypeTitle.value = '全部'
}

// 确定
const onConfirm = async () => {
  //关闭dropdown-menu
  districtDropdown.value.close()

  pageNum.value = 1 // 页码重置为1
  cinemas.value = [] // 清空电影院列表
  finished.value = false // 重置finished状态
  await getMovieCinemaListByFilter(
    offset.value,
    limit.value,
    activeShowDate.value,
    movieId.value,
    sort.value,
    store.currentCity.id,
    store.geolocation.latitude,
    store.geolocation.longitude,
    districtId.value,
    lineId.value,
    areaId.value,
    stationId.value,
    brandIds.value,
    serviceIds.value,
    hallTypeIds.value,
    languageIds.value,
    dimIds.value,
  )
};

const goToCinemaDetail = (cinemaId) => {
  // console.log('goToCinemaDetail', cinemaId)
  router.push({ path: `/cinema/${cinemaId}`, query: { showDate: activeShowDate.value, movieId: movieId.value } })

};



</script>

<style scoped>
/*************************** 特色 *******************/
.special {
  padding: 10px;
  color: #777;
}

.special h5 {
  font-size: 14px;
  margin: 0 0 10px 0;
  font-weight: normal;
}

.special .special-btn {
  font-size: 10px;
  /* text-overflow: ellipsis;
  overflow: hidden;
  white-space: nowrap; */
}

.van-grid {
  color: #777;
}

.van-grid-item {
  cursor: pointer;
}

/**** 选中的按钮*****/
.active-btn {
  color: #e54847 !important;
  background: #fcf0f0 !important;
  border: #f03d37 !important;
}

.reset {
  width: 80px;
  height: 36px;
  padding: 5px;
}

.confirm {
  width: 80px;
  height: 36px;
  padding: 5px;
  background-color: #e54847;
  color: #fff !important;
}

.line-ellipsis {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}


ul {
  padding: 0 10px;
  background-color: #fff;
}

.cinema-item {
  cursor: pointer;
  border-bottom: 1px solid #e8e8e8;
  display: flex;
  flex-direction: column;
  padding: 10px 0;
}


.name-price {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin: 5px 0 10px 0;
}

.name {

  font-size: 16px;
  color: #000;
}

.price {
  color: #f03d37;
  font-size: 18px;
}

.price span {
  font-size: 12px;
}

.address-distance {
  display: flex;
  justify-content: space-between;
  align-items: center;
  color: #666;
  font-size: 13px;
  margin-bottom: 5px;

}

.services {
  margin-bottom: 5px;
}

.service {
  margin-right: 5px;
  font-size: 12px;
}

.showTimes {
  vertical-align: middle;
  font-size: 12px;
  color: #999;
}
</style>
